// app/model/organization_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, TEXT, DATE } = app.Sequelize;

  const Organization = app.model.define('organization', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: STRING(200),
      allowNull: false,
      comment: '组织/公司名称'
    },
    code: {
      type: STRING(100),
      unique: true,
      comment: '组织编码'
    },
    description: {
      type: TEXT,
      comment: '组织描述'
    },
    contactInfo: {
      type: TEXT,
      field: 'contact_info',
      comment: '联系信息'
    },
    address: {
      type: STRING(500),
      comment: '地址'
    },
    status: {
      type: INTEGER,
      defaultValue: 1,
      comment: '状态:1启用,0禁用'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'organizations',
    timestamps: true,
    underscored: true
  });

  // 添加关联关系
  Organization.associate = function() {
    // 组织与用户的多对多关系
    if (app.model.UserModel && app.model.UserOrganizationModel) {
      Organization.belongsToMany(app.model.UserModel, {
        through: app.model.UserOrganizationModel,
        foreignKey: 'organization_id',
        otherKey: 'user_id',
        as: 'users'
      });
    }

    // 组织与客户的关联（一对多）
    if (app.model.CustomerModel) {
      Organization.hasMany(app.model.CustomerModel, {
        foreignKey: 'organization_id',
        as: 'customers'
      });
    }

    // 组织与销售订单的关联（一对多）
    if (app.model.SalesOrderModel) {
      Organization.hasMany(app.model.SalesOrderModel, {
        foreignKey: 'organization_id',
        as: 'salesOrders'
      });
    }
  };

  return Organization;
};